import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    "Content-Type": "application/json;charset:utf-8;"
  },
  timeout: 30000
})
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    return response
  },

  error => {
    if (error.message.indexOf("401") != -1 && localStorage.getItem('token')) {
      localStorage.clear()
      MessageBox.confirm('登录已过期，请重新登录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }
    return Promise.reject(error)
  }
)

export default service
